<template>
  <el-dialog
    v-model="visible"
    :title="dialogTitle"
    width="800px"
    :before-close="handleClose"
    append-to-body
    destroy-on-close
    class="kpi-detail-dialog"
  >
    <!-- 数字型指标详情 -->
    <div v-if="isNumericMetric" class="numeric-detail">
      <div class="metric-header">
        <div class="metric-value-large">
          {{ currentValue }}
          <span class="metric-unit">{{ unit }}</span>
        </div>
        <div class="metric-trend">
          <el-tag :type="trendType" size="large">
            <el-icon><Top v-if="trend === 'up'" /><Bottom v-else /></el-icon>
            {{ trendText }}
          </el-tag>
        </div>
      </div>
      
      <!-- 趋势图表 -->
      <div class="trend-chart-container">
        <div ref="trendChartRef" class="trend-chart"></div>
      </div>
      
      <!-- 相关说明 -->
      <div class="metric-description">
        <h4>指标说明</h4>
        <p>{{ metricDescription }}</p>
      </div>
    </div>
    
    <!-- 图表型指标详情（全屏展示） -->
    <div v-else class="chart-detail">
      <div ref="fullChartRef" class="full-chart"></div>
    </div>
    
    <template #footer>
      <el-button @click="handleClose">关闭</el-button>
      <el-button type="primary" @click="handleExport">
        <el-icon><Download /></el-icon>
        导出数据
      </el-button>
    </template>
  </el-dialog>
</template>

<script>
import { ref, computed, watch, nextTick } from 'vue'
import * as echarts from 'echarts'
import { Top, Bottom, Download } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

export default {
  name: 'KpiDetailDialog',
  components: {
    Top,
    Bottom,
    Download
  },
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    metricType: {
      type: String,
      default: ''
    },
    metricData: {
      type: Object,
      default: () => ({})
    }
  },
  emits: ['update:modelValue'],
  setup(props, { emit }) {
    const trendChartRef = ref(null)
    const fullChartRef = ref(null)
    let chartInstance = null
    
    const visible = computed({
      get: () => props.modelValue,
      set: (val) => emit('update:modelValue', val)
    })
    
    // 判断是否为数字型指标
    const isNumericMetric = computed(() => {
      const numericTypes = ['planCycle', 'planTotalHours', 'planOrderCount', 'planDeviceCount', 'planScore', 'orderAvgHours']
      return numericTypes.includes(props.metricType)
    })
    
    // 对话框标题
    const dialogTitle = computed(() => {
      const titles = {
        planCycle: '计划完成周期详情',
        planTotalHours: '计划总工时详情',
        planOrderCount: '计划订单数量详情',
        planDeviceCount: '计划设备数量详情',
        planScore: '计划分值详情',
        orderAvgHours: '订单平均工时详情',
        orderCompletion: '订单完成率分析',
        deviceCapacity: '设备产能利用率分析',
        devicePlan: '设备计划利用率分析'
      }
      return titles[props.metricType] || '指标详情'
    })
    
    // 当前值
    const currentValue = computed(() => {
      return props.metricData.value || 0
    })
    
    // 单位
    const unit = computed(() => {
      const units = {
        planCycle: '天',
        planTotalHours: '小时',
        planOrderCount: '个',
        planDeviceCount: '台',
        planScore: '分',
        orderAvgHours: '小时/单'
      }
      return units[props.metricType] || ''
    })
    
    // 趋势
    const trend = computed(() => {
      return props.metricData.trend || 'up'
    })
    
    const trendType = computed(() => {
      return trend.value === 'up' ? 'success' : 'danger'
    })
    
    const trendText = computed(() => {
      const percentage = props.metricData.trendPercentage || 5
      return `${trend.value === 'up' ? '↑' : '↓'} ${percentage}%`
    })
    
    // 指标说明
    const metricDescription = computed(() => {
      const descriptions = {
        planCycle: '从计划开始到完成所需的总天数，包含所有工序的加工时间和等待时间。',
        planTotalHours: '完成当前计划所需的总工时，是所有订单工时的累计值。',
        planOrderCount: '当前计划包含的订单总数量。',
        planDeviceCount: '参与当前计划的设备总数量。',
        planScore: '基于多个维度（交期、产能、利用率等）计算的综合评分，满分100分。',
        orderAvgHours: '每个订单平均需要的加工工时。'
      }
      return descriptions[props.metricType] || '暂无说明'
    })
    
    // 初始化趋势图表
    const initTrendChart = () => {
      if (!trendChartRef.value) return
      
      chartInstance = echarts.init(trendChartRef.value)
      
      // 生成模拟趋势数据
      const dates = []
      const values = []
      const baseValue = currentValue.value
      
      for (let i = 30; i >= 0; i--) {
        const date = new Date()
        date.setDate(date.getDate() - i)
        dates.push(date.toLocaleDateString('zh-CN', { month: '2-digit', day: '2-digit' }))
        
        // 生成波动数据
        const fluctuation = (Math.random() - 0.5) * baseValue * 0.1
        values.push(Math.round(baseValue + fluctuation))
      }
      
      const option = {
        tooltip: {
          trigger: 'axis'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: dates,
          axisLabel: {
            interval: 5
          }
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: `{value} ${unit.value}`
          }
        },
        series: [
          {
            name: dialogTitle.value.replace('详情', ''),
            type: 'line',
            smooth: true,
            data: values,
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: 'rgba(113, 75, 103, 0.3)' },
                { offset: 1, color: 'rgba(113, 75, 103, 0.05)' }
              ])
            },
            itemStyle: {
              color: '#714B67'
            },
            markLine: {
              data: [
                { type: 'average', name: '平均值' }
              ]
            }
          }
        ]
      }
      
      chartInstance.setOption(option)
    }
    
    // 初始化全屏图表
    const initFullChart = () => {
      if (!fullChartRef.value || !props.metricData.chartData) return
      
      chartInstance = echarts.init(fullChartRef.value)
      
      // 根据不同的图表类型设置选项
      let option = {}
      
      if (props.metricType === 'orderCompletion') {
        // 订单完成率折线图（增强版）
        option = {
          title: {
            text: '各订单计划履约完成率趋势',
            left: 'center'
          },
          tooltip: {
            trigger: 'axis'
          },
          legend: {
            bottom: 10
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '15%',
            top: '10%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            boundaryGap: false,
            data: props.metricData.chartData[0]?.data.map(item => item.date) || []
          },
          yAxis: {
            type: 'value',
            max: 100,
            axisLabel: {
              formatter: '{value}%'
            }
          },
          series: props.metricData.chartData.map((order, index) => ({
            name: order.name,
            type: 'line',
            smooth: true,
            data: order.data.map(item => item.value),
            itemStyle: {
              color: getOrderColor(index)
            }
          }))
        }
      } else if (props.metricType === 'deviceCapacity' || props.metricType === 'devicePlan') {
        // 设备利用率柱状图（增强版）
        const title = props.metricType === 'deviceCapacity' ? '各设备产能利用率' : '各设备计划利用率'
        const color = props.metricType === 'deviceCapacity' ? ['#409EFF', '#66B1FF'] : ['#67C23A', '#85CE61']
        
        option = {
          title: {
            text: title,
            left: 'center'
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            top: '10%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: props.metricData.chartData.map(item => item.name)
          },
          yAxis: {
            type: 'value',
            max: 100,
            axisLabel: {
              formatter: '{value}%'
            }
          },
          series: [
            {
              name: title,
              type: 'bar',
              data: props.metricData.chartData.map(item => item.value),
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: color[0] },
                  { offset: 1, color: color[1] }
                ])
              },
              label: {
                show: true,
                position: 'top',
                formatter: '{c}%'
              }
            }
          ]
        }
      }
      
      chartInstance.setOption(option)
    }
    
    const getOrderColor = (index) => {
      const colors = ['#714B67', '#409EFF', '#67C23A', '#E6A23C', '#F56C6C']
      return colors[index % colors.length]
    }
    
    // 处理关闭
    const handleClose = () => {
      visible.value = false
    }
    
    // 导出数据
    const handleExport = () => {
      ElMessage.success('数据导出功能开发中...')
    }
    
    // 监听对话框显示状态
    watch(visible, (val) => {
      if (val) {
        nextTick(() => {
          if (isNumericMetric.value) {
            initTrendChart()
          } else {
            initFullChart()
          }
        })
      } else {
        // 销毁图表实例
        if (chartInstance) {
          chartInstance.dispose()
          chartInstance = null
        }
      }
    })
    
    return {
      visible,
      trendChartRef,
      fullChartRef,
      isNumericMetric,
      dialogTitle,
      currentValue,
      unit,
      trend,
      trendType,
      trendText,
      metricDescription,
      handleClose,
      handleExport
    }
  }
}
</script>

<style scoped>
.kpi-detail-dialog {
  /* 自定义样式 */
}

.numeric-detail {
  padding: 20px;
}

.metric-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.metric-value-large {
  font-size: 48px;
  font-weight: 700;
  color: #303133;
}

.metric-unit {
  font-size: 24px;
  font-weight: 400;
  margin-left: 8px;
  color: #909399;
}

.metric-trend {
  text-align: right;
}

.trend-chart-container {
  margin-bottom: 30px;
}

.trend-chart {
  width: 100%;
  height: 300px;
}

.metric-description {
  background: #f5f7fa;
  border-radius: 4px;
  padding: 20px;
}

.metric-description h4 {
  margin: 0 0 10px;
  color: #303133;
}

.metric-description p {
  margin: 0;
  color: #606266;
  line-height: 1.6;
}

.chart-detail {
  padding: 20px;
}

.full-chart {
  width: 100%;
  height: 500px;
}
</style>
